﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace ITJZ.BitHelper.Tools
{
    /// <summary>
    /// 序列化助手类
    /// </summary>
    public  class XmlSerializerHelper
    {
        /// <summary>
        /// 把一个对象序列化为xml文档格式
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string Serialize(object o)
        {
            string res = string.Empty;

            using (MemoryStream ms = new MemoryStream())
            {
                string temp = o.GetType().FullName;
                Type tt = Type.GetType(temp);
                new XmlSerializer(Type.GetType(o.GetType().FullName)).Serialize(ms, o);

                byte[] bs = ms.ToArray();

                res = Encoding.UTF8.GetString(bs);
            }

            return res;
        }

        public static object DeSerialize(Type type, string bin)
        {
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(bin);
            using (MemoryStream ms=new MemoryStream ( bs))
            {
                ms.Position = 0;

                return new XmlSerializer(type).Deserialize(ms);
            }
             
        }
    }
}
